package com.example.cp.controller;

import com.example.cp.pojo.WxMessage;
import com.example.cp.service.SendMsgService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.bean.WxCpMessageSendResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 * Created by hemin on 2019/8/9.
 */
@RestController
@RequestMapping("/sendMsg")
@Slf4j
public class MessageController {

    @Autowired
    SendMsgService sendMsgService;

    /**
     * 发送文本消息
     * @return
     */
    @PostMapping("/text")
    public WxCpMessageSendResult sendText(@RequestBody WxMessage wxMessage){
        try {
            return sendMsgService.text(wxMessage.getAgentId(), wxMessage.getUserIds(), wxMessage.getContent());
        } catch (WxErrorException e) {
            WxCpMessageSendResult sendResult = new WxCpMessageSendResult();
            sendResult.setErrCode(1);
            sendResult.setErrMsg("发送消息失败");
            sendResult.setInvalidUser(wxMessage.getUserIds());
            return sendResult;
        }
    }

    /**
     * 发送卡片文本消息
     * @return
     */
    @PostMapping("/textCard")
    public WxCpMessageSendResult sendTextCard(@RequestBody WxMessage wxMessage){
        try {
            return sendMsgService.textCard(wxMessage.getTitle(),wxMessage.getDescription(),wxMessage.getUrl(),wxMessage.getAgentId(),wxMessage.getUserIds(),wxMessage.getBtnText());
        } catch (WxErrorException e) {
            WxCpMessageSendResult sendResult = new WxCpMessageSendResult();
            sendResult.setErrCode(1);
            sendResult.setErrMsg(e.getMessage());
            sendResult.setInvalidUser(wxMessage.getUserIds());
            return sendResult;
        }
    }
}
